﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using MySql.Data.MySqlClient;


namespace LectorHuellaC
{
    public partial class GenerarCodigoBarras : Form
    {
        string IdEmpleado;
        public bool aceptcodigo;
        public string codigo_barras;
        String versionapp = "A 1.0";
        log4net.ILog logger;

        string statusConection;

        public void tipoConexion(String conection)
        {
            statusConection = conection;
            label4.Text = statusConection;
        }

        public GenerarCodigoBarras(string IdEmpleado)
        {
            log4net.Config.XmlConfigurator.Configure();
            logger = log4net.LogManager.GetLogger(typeof(Program));
            this.IdEmpleado = IdEmpleado;
            InitializeComponent();
            generarCodigoAleatorio();
            cargarDatosUsuario();
            this.Text = ":: Reloj Checador :: " + versionapp +" ("+this.Text+")";
        }

        private void btGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                GenerateBarCode();
                btnAceptar.Enabled = true;
            }catch(Exception ex)
            {
                logger.Error("error" + ex);
            }
        }

        public void cargarDatosUsuario()
        {
            string IdEmpresa = Settings1.Default.IdEmpresa;
            string IdSucursal = Settings1.Default.IdSucursal;
            String sql;
            MySqlConnection cn;
            MySqlCommand cm;
            MySqlDataAdapter da;
            //DataSet ds;
            sql = "Select IdEmpleado, empresa,nombre,imagen_empleado "
            + "from datosempleado where  IdEmpleado='" + this.IdEmpleado + "' and idempresa='"+IdEmpresa+"' and idsucursal='"+IdSucursal+"'";
            cn = new MySqlConnection("Data Source=localhost;Database=soltec_centralfra;User ID=root; Password=root; Allow Zero Datetime=True; CHARSET=latin1");
            cn.Open();

            cm = new MySqlCommand();
            cm.CommandText = sql;
            cm.CommandType = CommandType.Text;
            cm.Connection = cn;
            da = new MySqlDataAdapter(cm);
            DataTable datos = new DataTable();
            da.Fill(datos);
            lblname.Text = datos.Rows[0]["nombre"].ToString();
        }

        private void GenerateBarCode()
        {
            this.Cursor = Cursors.WaitCursor;
            statbar.Panels[0].Text = "Generating barcode...";


            //WSBarcodeGenerator.BarCodeGenerator barCodeGen = new WSBarcodeGenerator.BarCodeGenerator();

            int barSize = System.Convert.ToInt32(txtFontSize.Text);

            //System.Byte[] imgBarcode = barCodeGen.Code39(txtCode.Text, barSize, chkBoxShowBarcode.Checked, txtTitle.Text);
            System.Byte[] imgBarcode = Code39(txtCode.Text, barSize, chkBoxShowBarcode.Checked, txtTitle.Text);
            MemoryStream memStream = new MemoryStream(imgBarcode);

            pictBox.Image = new Bitmap(memStream);

            statbar.Panels[0].Text = "Done.";
            this.Cursor = Cursors.Default;
        }

        public byte[] Code39(string code, int barSize, bool showCodeString, string title)
        {

            Code39 c39 = new Code39();

            // Create stream....
            MemoryStream ms = new MemoryStream();
            c39.FontFamilyName = Settings1.Default.BarCodeFontFamily.ToString();
            c39.FontFileName = Settings1.Default.BarCodeFontFile.ToString();


            c39.FontSize = barSize;
            c39.ShowCodeString = showCodeString;
            if (title + "" != "")
                c39.Title = title;
            Bitmap objBitmap = c39.GenerateBarcode(code);
            objBitmap.Save(ms, ImageFormat.Png);

            //return bytes....
            return ms.GetBuffer();
        }

        public void generarCodigoAleatorio(){
            Random r = new Random(DateTime.Now.Millisecond);

            int aleatorio = r.Next(2, 300);
            txtCode.Text = Convert.ToString(aleatorio) + this.IdEmpleado;
          
        }

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            string IdEmpresa = Settings1.Default.IdEmpresa;
            string IdSucursal = Settings1.Default.IdSucursal;

            ConectaBD conBD = new ConectaBD();
            //byte[] bits_images = convertPicBoxImageToByte(pbUsuario);
            //byteBLOBData = (Byte[])(bits_images);
            //String s = System.Text.Encoding.UTF8.GetString(bits_images);
            string sentencia = "update reloj_empleados set claveentrada=?claveentrada," 
                               +" imagen_empleado=?imagen_empleado where " 
                               + " IdEmpleado=?IdEmpleado and idsucursal=?idsucursal and idempresa=?idempresa";

            MySqlConnection cn = new MySqlConnection("Data Source=localhost;Database=soltec_centralfra;User ID=root; Password=root; Allow Zero Datetime=True; CHARSET=latin1");
            cn.Open();

            MySqlCommand cmd = new MySqlCommand(sentencia, cn);

            cmd.Parameters.Add("?imagen_empleado", MySqlDbType.Blob);
            //cmd.Parameters["?imagen_empleado"].Value = bits_images;

            cmd.Parameters.Add("?IdEmpleado", MySqlDbType.VarChar);
            cmd.Parameters["?IdEmpleado"].Value = this.IdEmpleado;

            cmd.Parameters.Add("?claveentrada", MySqlDbType.VarChar);
            cmd.Parameters["?claveentrada"].Value = txtCode.Text;

            cmd.Parameters.Add("?idempresa", MySqlDbType.VarChar);
            cmd.Parameters["?idempresa"].Value = IdEmpresa;

            cmd.Parameters.Add("?idsucursal", MySqlDbType.VarChar);
            cmd.Parameters["?idsucursal"].Value = IdSucursal;

            int numRowsAffected=cmd.ExecuteNonQuery();
            cn.Close();
            if (numRowsAffected > 0) {
                MessageBox.Show("Actualizacion de los datos correcta", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnGenCred.Enabled = true;
            }
          
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Desea salir realmente?", "Confirmar Salir", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.Close();
                this.Dispose();
            }
        }

        private void btnimp_Click(object sender, EventArgs e)
        {
            if (!(pictBox.Image == null))
            {
                PrintDocument DocImprimir = new PrintDocument();
                PrintDialog printDialog1 = new PrintDialog();
                printDialog1.Document = DocImprimir;
                DialogResult result = printDialog1.ShowDialog();
                DocImprimir.PrintPage += new PrintPageEventHandler(DocImprimir_PrintPage);
                DocImprimir.Print();
            }
            else
            {
                MessageBox.Show("No ha generado aun la imagen", "Reloj Checador", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DocImprimir_PrintPage(object sender, PrintPageEventArgs e)
        {
             byte [] n=convertPicBoxImageToByte(pictBox);
             MemoryStream ms = new MemoryStream(n);
             Image returnImage = Image.FromStream(ms);
             int x = 100;
             int y = 100;
             e.Graphics.DrawImage(returnImage, x, y);
        }

        private byte[] convertPicBoxImageToByte(System.Windows.Forms.PictureBox pbImage)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            pbImage.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String sql;
            MySqlConnection cn;
            MySqlCommand cm;
            MySqlDataAdapter da;
            CRPCredencial reportCred = new CRPCredencial();
            string IdEmpresa = Settings1.Default.IdEmpresa;
            string IdSucursal = Settings1.Default.IdSucursal;

            //String id_user = PrintCellRowAndCol();
            if (!this.IdEmpleado.Equals(""))
            {
                ReportCredencial rpCD = new ReportCredencial();


                sql = "Select IdEmpleado, empresa,nombre,imagen_empleado "
                      + "from datosempleado where  IdEmpleado=?idempleado " 
                      + " and idempresa=?idempresa and idsucursal=idsucursal "; 
                cn = new MySqlConnection("Data Source=localhost;Database=soltec_centralfra;User ID=root; Password=root; Allow Zero Datetime=True; CHARSET=latin1");
                cn.Open();

                cm = new MySqlCommand();
                cm.CommandText = sql;
                cm.CommandType = CommandType.Text;
                cm.Connection = cn;
                cm.Parameters.Add("?IdEmpleado", MySqlDbType.VarChar);
                cm.Parameters["?IdEmpleado"].Value = this.IdEmpleado;

                 cm.Parameters.Add("?idempresa", MySqlDbType.VarChar);
                cm.Parameters["?idempresa"].Value = IdEmpresa;

                 cm.Parameters.Add("?idsucursal", MySqlDbType.VarChar);
                 cm.Parameters["?idsucursal"].Value = IdSucursal;
                da = new MySqlDataAdapter(cm);
                DataTable table = new DataTable();
                da.Fill(table);
                reportCred.SetDataSource(table);
                rpCD.crpCredencial.ReportSource = reportCred;
                rpCD.crpCredencial.RefreshReport();
                rpCD.Show();
            }
        }

        /**
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            // Se muestra al usuario esperando una acción

            DialogResult result = dialog.ShowDialog();
            // Si seleccionó un archivo (asumiendo que es una imagen lo que seleccionó)
            // la mostramos en el PictureBox de la inferfaz

            if (result == DialogResult.OK)
            {
                this.pbUsuario.Image = Image.FromFile(dialog.FileName);
            }
        }**/

    }
}
